import { Card, Breadcrumb, Form, Button, Space, Input, Radio, Upload, Modal, message } from 'antd';
import React, { Component, createRef } from 'react';
import styles from './index.module.scss';
import { Link } from 'react-router-dom';
import Channel from 'components/Channel';
import ReactQuill from 'react-quill';
import { PlusOutlined } from '@ant-design/icons';
import 'react-quill/dist/quill.snow.css';
import { baseURL } from 'utils/request';
import { addArticle, getArticleById, editArticleById } from 'api/article';

export default class ArticlePublish extends Component {
  state = {
		// 文章的封面类型
		type: 1,
		// 存放图片url
		fileList: [
			{
				url: ''
			}
		],
		previewVisible: false,
    previewUrl: '',
    // 编辑id
    id:this.props.match.params.id
	};

	formRef = React.createRef();

	changeType = (e) => {
		this.setState({
			type: e.target.value,
			// 切换按钮重置图片上传
			fileList: []
		});
	};

	uplooadImg = ({ fileList }) => {
		// 添加上传图片到state
		this.setState({
			fileList
		});
	};

	// 预览功能
	handlePreview = (file) => {
		const url = file.url || file.response.data.url;
		// console.log(file)
		this.setState({
			previewVisible: true,
			previewUrl: url
		});
	};

	// 限制图片上传大小及格式
	beforeUpload = (file) => {
		console.log(file);
		if (file.size >= 1024 * 500) {
			message.warning('上传的图片必须小于500kb');
			return Upload.LIST_IGNORE;
		}
		if (!['image/png', 'image/jepg'].includes(file.type)) {
			message.warning('只支持png或jpeg格式图片');
			return Upload.LIST_IGNORE;
		}
		return true;
	};

	save = async (values, draft) => {
		const { type, fileList } = this.state;
		// console.log(values);
    if (fileList.length !== type) return message.warning('上传图片数量不符');

		// 得到图片url
    const images = fileList.map((item) => item.url || item.response.data.url);
    
    if (this.state.id) {
      await editArticleById(
				{
					...values,
					cover: {
						type,
						images
					},
          id:this.state.id,
        },
				draft
      );
		message.success('修改成功');
     } else {
       await addArticle(
					{
						...values,
						cover: {
							type,
							images
						}
					},
					draft
				);
        message.success('添加成功');
			}
		this.props.history.push('/home/list');
	};

	onFinish = async (values) => {
		this.save(values, false);
		// console.log(res);
	};
	addDraft = async () => {
		const values = await this.formRef.current.validateFields();
		this.save(values, true);
  };
  
  async componentDidMount () {
    if (this.state.id) {
      const res = await getArticleById(this.state.id);
			// console.log(res);
      const values={...res.data,type:res.data.cover.type}
      this.formRef.current.setFieldsValue(values);

      const fileList = res.data.cover.images.map(item => ({ url: item }))
      this.setState({fileList,type:res.data.cover.type})

   }
  }

  render () {
		return (
			<div className={styles.root}>
				<Card
					title={
						<Breadcrumb separator="/">
							<Breadcrumb.Item>
								<Link to="/home">首页</Link>
							</Breadcrumb.Item>
							<Breadcrumb.Item>{this.state.id ? '编辑文章' : '发布文章'}</Breadcrumb.Item>
						</Breadcrumb>
					}
				>
					<Form
						ref={this.formRef}
						labelCol={{ span: 4 }}
						size="large"
						onFinish={this.onFinish}
						validateTrigger={['onBlur', 'onChange']}
						initialValues={{ content: '', type: this.state.type }}
					>
						<Form.Item
							label="标题"
							name="title"
							rules={[
								{
									required: true,
									message: '文章标题不能为空'
								}
							]}
						>
							<Input style={{ width: 400 }} placeholder="请输入文章标题"></Input>
						</Form.Item>
						<Form.Item
							label="频道"
							name="channel_id"
							rules={[
								{
									required: true,
									message: '请选择频道'
								}
							]}
						>
							<Channel />
						</Form.Item>
						<Form.Item label="封面" name="type">
							<Radio.Group onChange={this.changeType}>
								<Radio value={1}>单图</Radio>
								<Radio value={3}>三图</Radio>
								<Radio value={0}>无图</Radio>
							</Radio.Group>
						</Form.Item>
						<Form.Item wrapperCol={{ offset: 4 }}>
							{this.state.type !== 0 && (
								<Upload
									listType="picture-card"
									fileList={this.state.fileList}
									action={`${baseURL}upload`}
									name="image"
									onChange={this.uplooadImg}
									onPreview={this.handlePreview}
									beforeUpload={this.beforeUpload}
								>
									{this.state.fileList.length < this.state.type && <PlusOutlined />}
								</Upload>
							)}
						</Form.Item>
						<Form.Item
							label="内容"
							name="content"
							rules={[
								{
									required: true,
									message: '文章内容不能为空'
								}
							]}
						>
							<ReactQuill theme="snow" placeholder="请输入文章内容"></ReactQuill>
						</Form.Item>
						<Form.Item wrapperCol={{ offset: 4 }}>
							<Space>
								<Button type="primary" htmlType="submit" size="large">
									{this.state.id ? '编辑文章' : '发布文章'}
								</Button>
								<Button size="large" onClick={this.addDraft}>
									存入草稿
								</Button>
							</Space>
						</Form.Item>
					</Form>
				</Card>

				{/* 图片预览功能 */}
				<Modal visible={this.state.previewVisible} title="图片预览" footer={null} onCancel={() => this.setState({ previewVisible: false })}>
					<img alt="example" style={{ width: '100%' }} src={this.state.previewUrl} />
				</Modal>
			</div>
		);
	}
}
